package com.item.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.filter.LoginFilter;
import com.item.exception.JSONRepUtils;

public class CoreController {
	protected Logger logger = Logger.getLogger(getClass());
	
	@ExceptionHandler(value={Exception.class}) 
	@ResponseBody
    public String handleException(Exception ex,HttpServletRequest request) {  
		ex.printStackTrace();
        request.setAttribute("errorName", ex.toString()); 
        request.setAttribute("errorMsg", ex.getMessage()==null?"":ex.getMessage());
        return JSONRepUtils.serialize(ex);
    }
	
	@InitBinder  
    public void initBinder(WebDataBinder binder) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
    } 
	
	public String getAppId(HttpSession session) {
		Object obj = session.getAttribute(LoginFilter.SESSION_USER_KEY);
		if (obj != null) {
			HashMap<String, String> map = (HashMap<String, String>) obj;
			if (map.get("userType").equals("0")) {
				return "";
			} else {
				return map.get("appid");
			}
		}
		return "";
	}
	
	public String getSessionParameter(String name,HttpSession session) {
		Object obj = session.getAttribute(LoginFilter.SESSION_USER_KEY);
		if (obj != null) {
			HashMap<String, String> map = (HashMap<String, String>) obj;
			return map.get(name);
		}
		return "";
	}
	
	public void setSessionParameter(String name,String value,HttpSession session) {
		Object obj = session.getAttribute(LoginFilter.SESSION_USER_KEY);
		if (obj != null) {
			HashMap<String, String> map = (HashMap<String, String>) obj;
			map.put(name, value);
		}
	}
}
